import yaml
from PySide2.QtGui import QCursor, QPixmap
from PySide2.QtWidgets import QWidget, QFrame, QPushButton, QHBoxLayout, QGridLayout, \
    QLabel, QSizePolicy, QVBoxLayout, QStackedWidget, QSpacerItem, QCompleter, QScrollArea
from PySide2.QtCore import Qt
from PySide2.QtCore import QObject, Signal
from qfluentwidgets import PushButton, PrimaryPushButton, ComboBox, SpinBox, Pivot, SegmentedWidget, TitleLabel, BodyLabel, StrongBodyLabel, EditableComboBox, ScrollArea

from .ui_name_mappings import *
from .core import *
# from app.common.config import get_abs_path, get_all_children
from app.common.style_sheet import StyleSheet
from app.components.pivot_interface import PivotInterface

from utils import get_all_children, get_abs_path



def get_str_from_dict(data, sep=','):
    if data is None:
        return '无'
    s = ''
    for k, v in data.items():
        s += f'{k}: {v}' + sep
    return s[:-1]


def _get_resources_path(name, data):
    role = data['门派']
    if data['装备'][name] == '无':
        path = 'none;'
    elif name in ['头部', '衣服', '武器', '手部', '腰部', '鞋子']:
        path = f'url(:/gallery/images/img/装备/{role}/{name}.jpg)'
    elif name in ['护符1', '护符2', '令牌', '法印']:
        path = f'url(:/gallery/images/img/装备/通用/{name}.jpg)'
    return path


class MyIconFrame(QFrame):
    def __init__(self, parent=None):
        super(MyIconFrame, self).__init__(parent)
        btn = QPushButton(self)
        sizePolicy4 = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy4.setHorizontalStretch(0)
        sizePolicy4.setVerticalStretch(0)
        sizePolicy4.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy4)
        layout = QHBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(btn)
        self.btn = btn
        self.btn.setCursor(QCursor(Qt.PointingHandCursor))
        self.btn.setFixedSize(25,25)


class AttrWidget(QWidget):
    def __init__(self, parent=None):
        super(AttrWidget, self).__init__(parent=parent)
        self._parent = parent
        self.layout = QVBoxLayout(self)
        self.setLayout(self.layout)

        self.widget_title = QWidget(self)
        self.widget_title.setObjectName('widget_title')
        self.widget_role = QWidget(self)
        self.widget_hp = QWidget(self)
        self.widget_attr = QWidget(self)
        self.layout.addWidget(self.widget_title)
        self.layout.addWidget(self.widget_role)
        self.layout.addWidget(self.widget_hp)
        self.layout.addWidget(self.widget_attr)

        # 1 人物等级和名称
        layout_title = QHBoxLayout(self.widget_title)
        label = QLabel(self)
        label.setText('60')
        layout_title.addWidget(label)
        widget_title_right = QWidget(self.widget_title)
        layout_title_right = QVBoxLayout(widget_title_right)
        label_name = QLabel(self)
        label_chenghao = QLabel(self)
        label_touxian = QLabel(self)
        label_name.setText('燃烧的浅蓝')
        label_chenghao.setText("称号：神兽尊前主风云·真")
        label_touxian.setText("头衔：未使用")
        layout_title_right.addWidget(label_name)
        layout_title_right.addWidget(label_chenghao)
        layout_title_right.addWidget(label_touxian)
        layout_title.addWidget(widget_title_right)
        spacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout_title.addItem(spacer)

        # 2 门派、帮会和阵营

        # 3 气血体力和真气
        label1 = QLabel(self)
        label1.setText('气血')
        label2 = QLabel(self)
        label2.setText('99999/99999')
        label3 = QLabel(self)
        label3.setText('真气')
        label4 = QLabel(self)
        label4.setText('1000/1000')
        self.widget_hp.setLayout(QHBoxLayout())
        self.widget_hp.setObjectName('widget_hp')
        self.widget_hp.layout().addWidget(label1, 0, Qt.AlignLeft)
        self.widget_hp.layout().addWidget(label2, 0, Qt.AlignLeft)
        self.widget_hp.layout().addWidget(label3, 0, Qt.AlignLeft)
        self.widget_hp.layout().addWidget(label4, 0, Qt.AlignLeft)

        self.widget_attr_main = self._create_attr_widget(MAIN_ATTR_NAME_MAPPING, '主属性', self.widget_attr)
        self.widget_attr_linggen = self._create_attr_widget(LINGGEN_NAME_MAPPING, '灵根', self.widget_attr)
        self.widget_attr_attack = self._create_attr_widget(ATTACK_ATTR_NAME_MAPPING, '攻击', self.widget_attr)
        self.widget_attr_defend = self._create_attr_widget(DEFEND_ATTR_NAME_MAPPING, '防御', self.widget_attr)
        self.widget_attr_main.setObjectName('widget_attr_main')
        self.widget_attr_linggen.setObjectName('widget_attr_linggen')
        self.widget_attr_attack.setObjectName('widget_attr_attack')
        self.widget_attr_defend.setObjectName('widget_attr_defend')

        self.gridLayout = QGridLayout(self)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.widget_attr.setLayout(self.gridLayout)
        self.gridLayout.addWidget(self.widget_attr_main, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.widget_attr_linggen, 0, 1, 1, 1)
        self.gridLayout.addWidget(self.widget_attr_attack, 1, 0, 1, 1)
        self.gridLayout.addWidget(self.widget_attr_defend, 1, 1, 1, 1)

        self._setStyleSheet()

    def _create_attr_widget(self, mappings, title, parent):
        widget = QWidget(parent)
        widget.setFixedSize(250, 220)
        vboxLayout = QVBoxLayout(widget)
        vboxLayout.setContentsMargins(0, 10, 0, 10)
        widget.setLayout(vboxLayout)
        label_title = QLabel(parent)
        label_title.setText(title)
        label_title.setAlignment(Qt.AlignCenter)
        vboxLayout.addWidget(label_title)
        for ui_name, attr_name in mappings.items():
            frame = QFrame(widget)
            vboxLayout.addWidget(frame)
            frame_layout = QHBoxLayout(frame)
            frame_layout.setContentsMargins(20, 0, 20, 0)
            frame.setLayout(frame_layout)
            label1 = QLabel(widget)
            label1.setAlignment(Qt.AlignLeft)
            label2 = QLabel(widget)
            label2.setAlignment(Qt.AlignRight)
            label1.setText(attr_name)
            label2.setText(attr_name)
            frame.layout().addWidget(label1, 0, Qt.AlignLeft)
            frame.layout().addWidget(label2, 0, Qt.AlignRight)
            frame.setObjectName(f"frame_{ui_name}")
            widget.setStyleSheet("QFrame{background-color: transparent;}\n "
                                "QFrame::hover{background-color: rgba(40, 40, 40, 100);}"
                                "QLabel{background-color: transparent; font: 10pt 'Microsoft YaHei UI';}")
            label1.setAlignment(Qt.AlignCenter)
            setattr(self, 'label_{}'.format(ui_name), label2)
            label2.setObjectName("label_{}".format(ui_name))

        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        vboxLayout.addItem(spacer)
        return widget

    def _setStyleSheet(self):
        style_sheet = "QWidget { border-radius: 5px;}\n QLabel{background-color: transparent; font: 10pt 'Microsoft YaHei UI';}"
        for name in ['title', 'hp', 'attr_main', 'attr_linggen', 'attr_attack', 'attr_defend']:
            style_sheet += f"QWidget#widget_{name}" + "{background-color: rgba(0, 0, 0, 100);}\n"
        self.setStyleSheet(style_sheet)

    def update(self):
        pass


class MyEqpContentWin(QWidget):
    def __init__(self, ui_name, eqp_type, signal, parent=None):
        super(MyEqpContentWin, self).__init__(parent)
        self.data = self.parent().data
        self.ui_name = ui_name
        self.eqp_type = eqp_type
        self.signal = signal

        layout = QVBoxLayout(self)
        # widget1: 图标和选择框
        widget1 = QWidget(parent)
        layout.addWidget(widget1, 0, Qt.AlignTop)
        layout1 = QHBoxLayout(widget1)
        layout1.setContentsMargins(0, 10, 0, 10)
        widget1.setLayout(layout1)
        widget1.setObjectName("widget1")
        frame = MyIconFrame(widget1)
        btn = frame.btn
        btn.setFixedSize(40, 40)

        combox = ComboBox(widget1)
        combox.setFixedHeight(40)
        all_eqps = ALL_EQUIPMENTS_DATA[self.data['门派']][eqp_type]
        all_eqp_names = list(all_eqps.keys())
        combox.addItems(all_eqp_names)
        index_cur = all_eqp_names.index(self.data['装备'][eqp_type])
        combox.setCurrentIndex(index_cur)
        combox.currentIndexChanged.connect(self._modify_equipment)

        setattr(self, f'btn_{ui_name}_content', btn)
        setattr(self, f'combobox_{ui_name}', btn)
        btn.setObjectName(f'btn_{ui_name}_content')
        combox.setObjectName(f'combox_{ui_name}')
        layout1.addWidget(frame)
        layout1.addWidget(combox)

        # widget2: 龙魂符咒
        widget2 = QWidget(self)

        label = QLabel(widget2)
        widget2_ = QWidget(widget2)
        layout2 = QVBoxLayout(widget2)
        layout2.setContentsMargins(0, 10, 0, 10)
        layout2_ = QHBoxLayout(widget2)
        widget2.setLayout(layout2)
        widget2_.setLayout(layout2_)

        layout2.addWidget(label, 0, Qt.AlignTop|Qt.AlignLeft)
        layout2.addWidget(widget2_)
        widget2.setObjectName("widget2")

        label.setText('龙魂符')
        label_longhun = QLabel('龙魂符增加等级')
        spinbox = SpinBox(widget2_)
        spinbox.setValue(self.data['龙魂'].get(eqp_type, 0))
        frame = MyIconFrame(widget2_)
        spinbox.setSingleStep(5)
        setattr(self, f'spinbox_longhun_{ui_name}', spinbox)
        spinbox.setObjectName(f'spinbox_longhun_{ui_name}')
        spinbox.valueChanged.connect(self._modify_longhun)
        layout2_.addWidget(frame)
        layout2_.addWidget(spinbox)
        layout2_.addWidget(label_longhun)
        self.widget2 = widget2
        self.label_longhun = label_longhun

        layout.addWidget(widget2, 0, Qt.AlignTop)

        # widget3: 属性栏
        widget3 = QWidget(self)
        widget3.setObjectName("widget3")
        layout.addWidget(widget3, 0, Qt.AlignTop)
        layout3 = QHBoxLayout(widget3)
        widget3_1 = QWidget(widget3)
        widget3_2 = QWidget(widget3)
        widget3_3 = QWidget(widget3)
        layout3.addWidget(widget3_1)
        layout3.addWidget(widget3_2)
        layout3.addWidget(widget3_3)
        layout3_1 = QVBoxLayout(widget3_1)
        layout3_2 = QVBoxLayout(widget3_2)
        layout3_3 = QVBoxLayout(widget3_3)
        widget3_1.setLayout(layout3_1)
        widget3_2.setLayout(layout3_2)
        widget3_2.setLayout(layout3_3)

        layout3_1.setContentsMargins(0, 0, 0, 0)
        layout3_2.setContentsMargins(0, 0, 0, 0)
        layout3_2.setContentsMargins(0, 0, 0, 0)
        layout3.setContentsMargins(0, 10, 0, 10)
        self.widget3_1 = widget3_1
        self.widget3_2 = widget3_2
        self.widget3_3 = widget3_3

        # widget4: 特殊词条
        widget4 = QWidget(self)
        widget4.setObjectName("widget4")
        layout.addWidget(widget4, 0, Qt.AlignTop)
        layout4 = QVBoxLayout(widget4)

        # widget5: 灌注符
        if eqp_type in self.data['灌注'].keys():
            widget5 = QWidget(self)
            self.widget5 = widget5
            widget5.setObjectName("widget5")
            layout5 = QGridLayout(widget5)
            layout.addWidget(widget5, 0, Qt.AlignTop)
            guanzhu_names = self.data['灌注'][eqp_type]

            for i, guanzhu_name in enumerate(guanzhu_names):
                guanzhu_attr = ALL_GUANZHU_DATA[eqp_type][guanzhu_name]
                text = get_str_from_dict(guanzhu_attr)
                frame = MyIconFrame(widget5)
                box = ComboBox(widget5)
                label = QLabel(text)
                setattr(self, f'label_guanzhu_{eqp_type}_{i}', label)
                layout5.addWidget(frame, i, 0, 1, 1)
                layout5.addWidget(box, i, 1, 1, 1)
                layout5.addWidget(label, i, 2, 1, 1)

                index_cur = None
                for index, (k, v) in enumerate(ALL_GUANZHU_DATA[eqp_type].items()):
                    box.addItem(text=k)
                    if k == guanzhu_name:
                        index_cur = index
                box.setCurrentIndex(index_cur)
                box.setObjectName('combox_guanzhu_{}'.format(i))
                box.currentIndexChanged.connect(self._modify_guanzhu)

        # widget6 获取方式
        widget6 = QWidget(self)
        widget6.setObjectName("widget6")
        self.widget6 = widget6
        layout6 = QVBoxLayout(widget6)
        widget6.setLayout(layout6)
        label1 = QLabel(widget6)
        label2 = QLabel(widget6)
        label1.setText('获取方式')
        widget6.layout().addWidget(label1)
        widget6.layout().addWidget(label2)
        self.label_huoqu = label2
        layout.addWidget(widget6)

        self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        layout.addItem(self.verticalSpacer)
        self._setStyleSheet()

    def _modify_equipment(self):
        box = self.sender()
        text = box.currentText()
        self.data['装备'][self.eqp_type] = text
        self.signal.emit(self.data)

    def _modify_longhun(self):
        self.data['龙魂'][self.eqp_type] = self.sender().value()
        self.signal.emit(self.data)

    def _modify_guanzhu(self):
        box = self.sender()
        index = box.objectName().split('_')[-1]
        index = int(index)
        self.data['灌注'][self.eqp_type][index] = box.currentText()
        self.signal.emit(self.data)

    def _setStyleSheet(self):
        style_sheet = "QWidget { border-radius: 5px;}\n"
        for i in range(1, 6):
            style_sheet += f"QWidget#widget{i+1}"+"{background-color: rgba(20, 20, 20, 100);}\n" + \
                            f"QWidget#widget{i+1}::hover"+"{background-color: rgba(30, 30, 30, 100);}\n"
        self.setStyleSheet(style_sheet)

    def update(self):
        # 1 图标框
        ui_name = self.ui_name
        eqp_type = self.eqp_type
        btn = getattr(self, f'btn_{ui_name}_content')
        eqp_name = self.data['装备'][eqp_type]
        eqp_attr = ALL_EQUIPMENTS_DATA[self.data['门派']][self.eqp_type][eqp_name]

        btn.content = eqp_attr
        path = _get_resources_path(self.eqp_type, self.data)
        btn.setStyleSheet("border-image: %s" % path)

        # 2 龙魂符
        self.label_longhun.setText("装等: {} (+{})".format(eqp_attr['装等'], self.data['龙魂'].get(eqp_type, 0)))

        # 3 基础词条（核心属性、体、防御力+额外属性）
        for child in get_all_children(self.widget3_1):
            if isinstance(child, QLabel):
                child.deleteLater()
        for child in get_all_children(self.widget3_2):
            if isinstance(child, QLabel):
                child.deleteLater()
        for child in get_all_children(self.widget3_3):
            if isinstance(child, QLabel):
                child.deleteLater()
        label1 = QLabel(self.widget3_1)
        label2 = QLabel(self.widget3_2)
        label1.setText('基础属性')
        label2.setText('额外属性')
        self.widget3_1.layout().addWidget(label1)
        self.widget3_2.layout().addWidget(label2)
        attr_citiao = eqp_attr['属性']
        for k, v in attr_citiao.items():
            if k not in ATTACK_ATTR_NAMES:
                tgt_widget = self.widget3_1
            else:
                tgt_widget = self.widget3_2
            text = self._html_fmt(k, f"{v[0]}+{v[1]}")
            #
            # text = "{}: {} +{}".format(k, v[0], v[1])
            tgt_widget.layout().addWidget(QLabel(text))

        # 4 特殊词条

        # 5 灌注符咒
        if eqp_type in self.data['灌注'].keys():
            guanzhu_names = self.data['灌注'][eqp_type]
            for i, guanzhu_name in enumerate(guanzhu_names):
                label = getattr(self, f'label_guanzhu_{eqp_type}_{i}')
                guanzhu_attr = ALL_GUANZHU_DATA[eqp_type][guanzhu_name]
                text = get_str_from_dict(guanzhu_attr)
                label.setText(text)

        # 6 获取方式
        self.label_huoqu.setText(eqp_attr.get('获取途径', '无'))

    def _html_fmt(self, s1, s2):
        return "<p style=\"color:rgb(160,160,160);\">{}: <b style=\"color:white;\">{}</b></p>".format(s1, s2)


class MyOtherContenWin(QWidget):
    def __init__(self, parent):
        super(MyOtherContenWin, self).__init__(parent)
        self._parent = parent
        self.data = self._parent.data
        self.vBoxLayout = QVBoxLayout(self)

        # self.setLayout(self.vBoxLayout)

        # 套装属性
        self.widget_set, self.widget_set_box = self._create_widget(self, '套装属性')
        self.widget_xingpo, self.widget_xingpo_box = self._create_widget(self, '星魄属性')
        self.widget_fabao, self.widget_fabao_box = self._create_widget(self, '法宝属性')
        self.widget_food, self.widget_food_box = self._create_widget(self, '食物属性')
        self.widget_tianshu, self.widget_tianshu_box = self._create_widget(self, '天书属性')
        self.vBoxLayout.addWidget(self.widget_set)
        self.vBoxLayout.addWidget(self.widget_xingpo, 1, Qt.AlignTop)
        self.vBoxLayout.addWidget(self.widget_fabao)
        self.vBoxLayout.addWidget(self.widget_food)
        self.vBoxLayout.addWidget(self.widget_tianshu)

        self.widget_set.setObjectName("widget_set")
        self.widget_set_box.setObjectName("widget_set_box")
        self.widget_xingpo.setObjectName("widget_xingpo")
        self.widget_xingpo_box.setObjectName("widget_xingpo_box")
        self.widget_fabao.setObjectName("widget_fabao")
        self.widget_fabao_box.setObjectName("widget_fabao_box")
        self.widget_food.setObjectName("widget_food")
        self.widget_tianshu.setObjectName("widget_tianshu")
        self.widget_tianshu_box.setObjectName("widget_tianshu_box")

        # 套装
        for i, set_name in enumerate(self.data['装备套装']):
            combox = ComboBox(self.widget_set_box)
            items = list(ALL_EQUIPMENTS_DATA[self.data['门派']]['套装'].keys())
            combox.addItems(items)
            combox.setCurrentIndex(items.index(set_name))
            combox.setObjectName("combox_set_{}".format(i))
            combox.currentIndexChanged.connect(self._modify_set)
            label = QLabel(self.widget_set_box)
            label.setObjectName("label_set_{}".format(i))
            setattr(self, 'label_set_{}'.format(i), label)
            self.widget_set_box.layout().addWidget(combox, i, 0, 1, 1)
            self.widget_set_box.layout().addWidget(label, i, 1, 1, 1)

        # 星魄
        for i, (xingpo_type, xingpo_name) in enumerate(self.data['星魄'].items()):
            combox = ComboBox(self.widget_xingpo_box)
            items = list(ALL_XINGPO_DATA[xingpo_type].keys())
            combox.addItems(items)
            combox.setCurrentIndex(items.index(xingpo_name))
            combox.setObjectName("combox_xingpo_{}".format(i))
            combox.currentIndexChanged.connect(self._modify_xingpo)
            # combox.setMinimumHeight(50)
            label = QLabel(self.widget_xingpo_box)
            setattr(self, 'label_xingpo_{}'.format(i), label)
            self.widget_xingpo_box.layout().addWidget(combox, i, 0, 1, 1)
            self.widget_xingpo_box.layout().addWidget(label, i, 1, 1, 1)

        # 法宝
        self.combox_fabao = ComboBox(self.widget_fabao_box)
        items = list(ALL_FABAO_DATA.keys())
        self.combox_fabao.addItems(items)
        self.combox_fabao.setCurrentIndex(items.index(self.data['法宝']))
        self.combox_fabao.currentIndexChanged.connect(self._modify_fabao)
        self.label_fabao1 = QLabel(self.widget_fabao_box)
        self.label_fabao2 = QLabel(self.widget_fabao_box)
        self.widget_fabao_box.layout().addWidget(self.combox_fabao, 0, 0, 1, 1)
        self.widget_fabao_box.layout().addWidget(self.label_fabao1, 0, 1, 1, 1)
        self.widget_fabao_box.layout().addWidget(self.label_fabao2, 1, 0, 1, 2)

        # 食物
        for i, (food_type, food_name) in enumerate(self.data['食物'].items()):
            combox = ComboBox(self.widget_food_box)
            items = list(ALL_FOOD_DATA[food_type].keys())
            combox.addItems(items)
            combox.setCurrentIndex(items.index(food_name))
            combox.currentIndexChanged.connect(self._modify_food)
            label = QLabel(self.widget_food_box)
            setattr(self, 'label_food_{}'.format(i), label)
            label.setObjectName("label_food_{}".format(i))
            combox.setObjectName("combox_food_{}".format(i))
            self.widget_food_box.layout().addWidget(combox, i, 0, 1, 1)
            self.widget_food_box.layout().addWidget(label, i, 1, 1, 1)

        self._setStyleSheet()


    def _setStyleSheet(self):
        style_sheet = "QWidget { border-radius: 5px;}\n QLabel{background-color: transparent; font: 10pt 'Microsoft YaHei UI';}"
        for name in ['set', 'xingpo', 'fabao', 'tianshu', 'food']:
            style_sheet += f"QWidget#widget_{name}" + "{background-color: rgba(20, 20, 20, 100);}\n"
            style_sheet += f"QWidget#widget_{name}::hover" + "{background-color: rgba(30, 30, 30, 100);}\n"
        self.setStyleSheet(style_sheet)

    def _create_widget(self, parent, title):
        widget = QWidget(parent)
        vlayout = QVBoxLayout(widget)
        label1 = QLabel(parent)
        label1.setText(title)
        vlayout.addWidget(label1)
        widget2 = QWidget(widget)
        vlayout.addWidget(widget2)
        gridLayout = QGridLayout(widget2)
        widget2.setLayout(gridLayout)

        gridLayout.setHorizontalSpacing(10)
        gridLayout.setVerticalSpacing(10)
        return widget, widget2

    def _modify_set(self):
        box = self.sender()
        index = box.objectName().split('_')[-1]
        index = int(index)
        self.data['装备套装'][index] = box.currentText()
        self._parent.dataSignal.emit(self.data)

    def _modify_xingpo(self):
        box = self.sender()
        index = box.objectName().split('_')[-1]
        index = int(index)
        xingpo_types = list(self.data['星魄'].keys())
        xingpo_type = xingpo_types[index]
        self.data['星魄'][xingpo_type] = box.currentText()
        self._parent.dataSignal.emit(self.data)

    def _modify_fabao(self):
        box = self.sender()
        self.data['法宝'] = box.currentText()
        self._parent.dataSignal.emit(self.data)

    def _modify_food(self):
        box = self.sender()
        index = box.objectName().split('_')[-1]
        index = int(index)
        food_type = list(self.data['食物'].keys())[index]
        self.data['食物'][food_type] = box.currentText()
        self._parent.dataSignal.emit(self.data)

    def update(self):
        self.data = self._parent.data

        # 套装属性
        for i, set_name in enumerate(self.data['装备套装']):
            label = getattr(self, 'label_set_{}'.format(i))
            set_attr = ALL_EQUIPMENTS_DATA[self.data['门派']]['套装'][set_name]
            if set_attr is None:
                label.setText('无')
            else:
                label.setText(str(set_attr[1]))

        # 星魄
        for i, (xingpo_type, xingpo_name) in enumerate(self.data['星魄'].items()):
            label = getattr(self, 'label_xingpo_{}'.format(i))
            xingpo_attr = ALL_XINGPO_DATA[xingpo_type][xingpo_name]
            text = get_str_from_dict(xingpo_attr, sep='\n')
            label.setText(text)

        # 法宝
        fabao_attr = ALL_FABAO_DATA[self.data['法宝']]
        if fabao_attr is not None:
            text1 = get_str_from_dict(fabao_attr['佩戴属性'])
            self.label_fabao1.setText(text1)
            text2 = "使用法宝的{}秒内，".format(fabao_attr["BUFF时间"])
            level = self.data['蕴宝']['蕴宝等级']
            for k, v in fabao_attr['BUFF'].items():
                v1 = eval(v) if isinstance(v, str) else v
                text2 += '{}提升{}，'.format(k, v1)
            self.label_fabao2.setText(text2)
            self.label_fabao2.setWordWrap(True)

        # 食物
        for i, (food_type, food_name) in enumerate(self.data['食物'].items()):
            food_att = ALL_FOOD_DATA[food_type][food_name]
            text = get_str_from_dict(food_att)
            label = getattr(self, 'label_food_{}'.format(i))
            label.setText(text)


class PeizhuangInterface(ScrollArea):
    dataSignal = Signal(dict)
    def __init__(self, config_path=None, parent=None):
        super(PeizhuangInterface, self).__init__(parent)

        # 读取配置文件
        if config_path is None:
            config_path = get_abs_path('AppData/peizhuang/default.yaml')
        self.config_path = config_path
        self.data = self.read_config()

        self.view = QWidget(self)
        self._layout = QHBoxLayout(self.view)
        self.view.setLayout(self._layout)

        self.__initWidget()

        # 当数据信号更改时，重写文件，并更新ui内容
        self.dataSignal.connect(self.update)
        self.dataSignal.emit(self.data)

    def update(self):
        print('Data is updated!')
        self.save_config()

        # 1 显示左侧的装备图标
        for ui_name, eqp_type in EQUIPMENT_NAME_MAPPING.items():
            btn = getattr(self, f'btn_{ui_name}')
            eqp_name = self.data['装备'][eqp_type]
            path = _get_resources_path(eqp_type, self.data)
            btn.setStyleSheet("border-image: %s"%path)
            # btn.setPixmap(QPixmap(path))
            btn.content = ALL_EQUIPMENTS_DATA[self.data['门派']][eqp_type][eqp_name]

        # 2-1 更新装备内容
        for eqp_index, (ui_name, eqp_type) in enumerate(EQUIPMENT_NAME_MAPPING.items()):
            widget = getattr(self, f'widget_eqp_{ui_name}')
            widget.update()

        # 2-2 更新其他内容
        self.widget_other_content.update()

        # 3 更新右侧面板
        self.widget_right.update()


    def read_config(self):
        with open(self.config_path, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
        return data

    def save_config(self):
        with open(self.config_path, 'w', encoding='utf-8') as f:
            yaml.dump(self.data, f, allow_unicode=True, sort_keys=False)

    def __initWidget(self):
        self.view.setObjectName('view')
        self.setObjectName('homeInterface')
        # StyleSheet.HOME_INTERFACE.apply(self)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        self._layout.setContentsMargins(0, 0, 0, 50)
        self._layout.setSpacing(40)
        self._layout.setAlignment(Qt.AlignTop)

        # 1左侧装备按钮界面
        self.widget_eqp = QWidget(self)
        self.widget_eqp.setObjectName('widget_eqp')
        self.widget_eqp_layout = QGridLayout(self.widget_eqp)
        self.widget_eqp_layout.setVerticalSpacing(50)
        self.widget_eqp_layout.setHorizontalSpacing(30)
        self.widget_eqp_layout.setContentsMargins(50, 50, 0, 0)
        # self.widget_eqp.setLayout(self.widget_eqp_layout)

        nrows = 6
        for i, (ui_name, eqp_type) in enumerate(EQUIPMENT_NAME_MAPPING.items()):
            frame = MyIconFrame(self.widget_eqp)
            btn = frame.btn
            btn.setFixedSize(60, 60)
            setattr(self, f'btn_{ui_name}', btn)
            btn.setObjectName(f'btn_{ui_name}')

            index_row = i % nrows
            index_col = i // nrows
            self.widget_eqp.layout().addWidget(frame, index_row, index_col, 1, 1)
            btn.clicked.connect(self._switch_to_eqp)
        # self.widget_eqp.setStyleSheet()

        # 2 中间详情界面
        self.widget_mid = PivotInterface(self)
        self.widget_mid.setObjectName('widget_mid')
        self.widget_mid.setMinimumWidth(500)

        # 主要显示区域
        # 2.1 装备信息窗口
        self.widget_eqp_content = QStackedWidget(self)
        self.widget_eqp_content.setObjectName('widget_eqp_content')
        for eqp_index, (ui_name, eqp_type) in enumerate(EQUIPMENT_NAME_MAPPING.items()):
            widget = MyEqpContentWin(ui_name, eqp_type, self.dataSignal, parent=self)
            setattr(self, f'widget_eqp_{ui_name}', widget)
            self.widget_eqp_content.addWidget(widget)

        # 2.2 其余细节设置
        self.widget_other_content = MyOtherContenWin(self)

        # 2 添加在一个窗口中
        self.widget_mid.addSubInterface(self.widget_eqp_content, 'widget_eqp_content', '装备配置')
        self.widget_mid.addSubInterface(self.widget_other_content, 'widget_other_content', '其他配置')
        self.widget_mid.stackedWidget.setCurrentWidget(self.widget_eqp_content)
        self.widget_mid.pivot.setCurrentItem('widget_eqp_content')

        # 3 右侧属性界面
        self.widget_right = AttrWidget(self)
        self.widget_right.layout.setContentsMargins(0, 50, 50, 50)
        self._layout.addWidget(self.widget_eqp, 0, Qt.AlignLeft | Qt.AlignTop)
        self._layout.addWidget(self.widget_mid, 0, Qt.AlignLeft | Qt.AlignTop)
        self._layout.addWidget(self.widget_right, 0, Qt.AlignLeft | Qt.AlignTop)
        self._layout.setSpacing(30)

        # StyleSheet.PEIZHUANG_INTERFACE.apply(self)

    def _switch_to_eqp(self):
        btn = self.sender()
        ui_name = btn.objectName().split('_')[-1]
        index = list(EQUIPMENT_NAME_MAPPING.keys()).index(ui_name)
        self.widget_eqp_content.setCurrentIndex(index)
        print('clicked {}'.format(btn.objectName()))

    def _modify_item(self, item):
        btn = self.sender()
        print('changed {}'.format(btn.objectName()))

    def _switch_to_page(self):
        btn = self.sender()
        index = btn.objectName().split('_')[-1]
        index = int(index)
        self.widget_main.setCurrentIndex(index)


